import store from '@/store'
import queryString from 'query-string'
import { createApiSign } from '@/utils'
import { getUserInfo } from '@/helper/loginManage'
import debounce from '@climblee/uv-ui/libs/function/debounce.js'

/**
 * @function http类
 * @param {Object} config Axios配置项
 * @param {Object} hooks 各节点hooks
 * @param {String} appSecret 接口验签key
 */
export default class HttpService {
  constructor (params) {
    this.config = params.config
    this.appSecret = params.appSecret
  }
  service (path = '', body = {}, method = 'POST') {
    return new Promise(resolve => {
      const data = this._getRequestConfigData(body)
      uni.request({
        url: `${this.config.baseURL}${path}`,
        data,
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        method,
        success: response => {
					if (response.data?._errCode === '200000') {
						uni.hideLoading()
						const routers = getCurrentPages()
						const currentRouter = routers[routers.length - 1]
						if (!currentRouter || currentRouter.route === 'pages/login/index') return
						let redirectUri = `/${currentRouter.route}`
						const querys = queryString.stringify(currentRouter.options)
						if (querys) {
							redirectUri += `?${querys}`
						}
						return debounce(() => {
							uni.redirectTo({
								url: `/pages/login/index?redirectUri=${encodeURIComponent(redirectUri)}`
							})
						})
					}
          resolve([response.data, null])
        },
        fail: error => {
          resolve([{}, error])
        }
      })
    })
  }
	amapService (path = '', params = {}, body = {}, method = 'GET') {
	  return new Promise(resolve => {
	    uni.request({
	      url: `${this.config.amapURL}${path}?${queryString.stringify(params)}`,
	      data: body,
	      method,
	      success: response => {
	        resolve([response.data, null])
	      },
	      fail: error => {
	        resolve([{}, error])
	      }
	    })
	  })
	}
  _getRequestConfigData (body) {
		const token = store.state.user.userInfo.token || getUserInfo('token')
    const data = {
      pid: store.state.pid,
      platform: store.state.platform,
      timestamp: +new Date(),
      ...body
    }
		if (token) {
			data.token = token
		}
    data.sign = createApiSign(this.appSecret, data)
    return data
  }
}